const local = require("../../../data/local");
const app = getApp();
Page({
  data: {
    // 音乐的播放状态
    isPlay: false,
    collected:false,
    shared:false
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var id = options.id;
    var data = local.postList[options.id];
    this.setData({
      data,
      postId: id,
      music: local.postList[options.id].music
    });
    this.onMusic();
    // 进入页面退出页面音乐播放按钮一致
    if (app.globalData.g_isPlay && app.globalData.g_currentId == id) {
      this.setData({
        isPlay: true
      });
    };
    /* 缓存存在，则取值
     不存在则 */
     let allCollected = wx.getStorageSync('allCollected');
     if(allCollected){
       let storageCollected = allCollected[id];
       this.setData({
         collected:storageCollected
       })
     }else{
       let allCollected ={
       };
       allCollected[id]=false;
       wx.setStorageSync('allCollected', allCollected);
     }
  },
  // 监听音乐播放
  onMusic() {
    var self = this;
    wx.onBackgroundAudioPlay((result) => {
      self.setData({
        isPlay: true
      });
      app.globalData.g_isPlay = true;
      app.globalData.g_currentId = self.data.postId;
    });
    wx.onBackgroundAudioPause((result) => {
      self.setData({
        isPlay: false
      })
      app.globalData.g_isPlay = false;
      app.globalData.g_currentId = null;
    });
    if (wx.stopBackgroundAudio()) {
      this.setData({
        
        isPlay: false
      })
    }
  },
  /* 收藏 */
  onCollect(){
    var allCollected = wx.getStorageSync('allCollected');
    var storageCollected = allCollected[this.data.postId];
    storageCollected = !storageCollected;
    allCollected[this.data.postId] = storageCollected;
    wx.setStorageSync("allCollected", allCollected);
    this.setData({
      collected:storageCollected
    })
  },
  /* 分享 */
  onShare(){
    this.setData({
      shared:!this.data.shared
    })
    wx.showActionSheet({
      itemList: ["分享到微信","分享到微博","分享到朋友圈"],
      itemColor: '#ffdd33',
      /* 成功分享--图案亮 */
      success:res=> {
        console.log(res.tapIndex);
        this.setData({
          shared:true
        })
      },
      /* 取消--图案不亮 */
      fail:err =>{
        this.setData({
          shared:false
        })
      }
    })
  },

  
 // 点击音乐播放
  playMusic() {
    var self = this;
    if (this.data.isPlay) {
      wx.stopBackgroundAudio();
      this.setData({
        isPlay: false
      });
    } else {
      wx.playBackgroundAudio({
        dataUrl: self.data.music.url,
        title: self.data.music.title,
        coverImgUrl: self.data.music.coverImgUrl
      });
      this.setData({
        isPlay: true
      });
    }
  }

})
